import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;

/**
 * @author gao
 * @date 2025/8/14 21:37
 */

public class EchoServer {
    // 创建Socket对象
    private DatagramSocket socket;

    public EchoServer(int port) throws SocketException {
        socket = new DatagramSocket(port);
    }

    // 启动服务器，完成业务逻辑
    public void start() throws IOException {
        System.out.println("服务器启动");
        while (true) {
            // 1、读取请求并解析
            DatagramPacket reqPacket = new DatagramPacket(new byte[4096], 4096);
            socket.receive(reqPacket);
            // 把DatagramPacket里面的数据解析成字符串
            String request = new String(reqPacket.getData(), 0, reqPacket.getLength());
            // 根据请求计算响应
            String response = process(request);
            // 把响应写回到客户端
            DatagramPacket resPacket = new DatagramPacket(response.getBytes(), response.getBytes().length, reqPacket.getSocketAddress());
            socket.send(resPacket);

            System.out.printf("[%s:%d] 请求: %s 响应: %s\n", reqPacket.getAddress(), reqPacket.getPort(), request, response);
        }
    }

    public String process(String request) {
        return request;
    }

    public static void main(String[] args) throws IOException {
        EchoServer server = new EchoServer(9090);
        server.start();
    }
}